package com.lma.crm.base.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.lma.crm.base.BaseDao;
import com.lma.crm.page.PageHibernateCallBack;

public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {

    private Class<?> beanClass;
    
    //在创建子类的时候会首先创建父类，调用父类的无惨构造方法
    //this在运行时指的事当前运行的对象，所以这里的this在运行的时候指的是子类对象
    public BaseDaoImpl() {
        
        //获得运行时的类型，被参数化的类型
        ParameterizedType paramType = (ParameterizedType) this.getClass().getGenericSuperclass();
        //获得所有泛型参数得到一个数组
        beanClass = (Class<?>) paramType.getActualTypeArguments()[0];
        
    }
    
    @Override
    public void save(T t) {
        this.getHibernateTemplate().save(t);        
    }

    @Override
    public void update(T t) {
        this.getHibernateTemplate().update(t);
    }

    @Override
    public void delete(T t) {
        this.getHibernateTemplate().delete(t);
    }

    @Override
    public void saveOrUpdate(T t) {
        this.getHibernateTemplate().saveOrUpdate(t);
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public List<T> findAll() {
        return this.getHibernateTemplate().find("from " + beanClass.getName());
    }

    @SuppressWarnings("unchecked")
    @Override
    public T findById(Serializable id) {
        return (T) this.getHibernateTemplate().get(beanClass, id);
    }

    @SuppressWarnings("unchecked")
    @Override
    public int getTotalRecord(String condition, Object[] params) {
        String hql = "select count(c) from " + beanClass.getName() + " c where 1 = 1 " + condition;
        List<Long> list = this.getHibernateTemplate().find(hql, params);
        return list.get(0).intValue();
    }

    @Override
    public List<T> findAll(String condition, Object[] params, int startIndex, int pageSize) {
        String hql = "from " + beanClass.getName() + " where 1 = 1" + condition;
        return this.getHibernateTemplate().execute(new PageHibernateCallBack<T>(hql, params, startIndex, pageSize));
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> findAll(String condition, Object[] params) {
        String hql = "from " + beanClass.getName() + " where 1 = 1 " + condition;
        return this.getHibernateTemplate().find(hql, params);
    }

}
